package com.demo.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.entity.Account;
import com.demo.mapper.AccountMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AsyncGenerateAccountService extends ServiceImpl<AccountMapper, Account> {
    private static final Logger logger = LoggerFactory.getLogger(AccountService.class);
    // 账号总数
    private static final int ACCOUNT_TOTAL_NUMBER = 1000000;
    // 每批次插入数量
    private static final int BATCH_INSERT_SIZE = 1000;

    @Async
    public void generateAccountAndSave() {
        // 异步生成账号和保存到数据库的逻辑
        // 1. 生成账号
        List<Account> accounts = new ArrayList<>();
        for(int i=0;i<ACCOUNT_TOTAL_NUMBER;i++){
            String  account = generateAccount(i);
            accounts.add(new Account(null,account));
            // 2. 保存到数据库
            // 达到批次插入数量则插入数据库
            if (accounts.size() == BATCH_INSERT_SIZE) {
                this.saveBatch(accounts);
                accounts.clear();
            }
        }
        // 将剩余的账号插入数据库
        if (!accounts.isEmpty()) {
            this.saveBatch(accounts);
        }
        logger.info("账号生成完毕！");
    }

    /**
     * 生成账号的方法
     * 账号由前缀8000，7位序号(不足7位前面补0)，后缀x组成
     *
     * @param seqNumber 序号
     * @return 生成的账号
     */
    private String generateAccount(int seqNumber) {
        return "8000" + String.format("%07d", seqNumber) + "x";
    }
}
